﻿using System;
using System.Text;
using System.Management;
using System.IO;
using System.Net;
using System.Diagnostics;
using System.Threading;
using System.Text.RegularExpressions;

namespace OperateCamera
{
    class common
    {



        public static Form1 app;

        public static bool webCamStatusOpen = false ;  //网络摄像头是否打开【非本地】

        public static System.Drawing.Size DefaultSize = new System.Drawing.Size(320, 240);

        // DateTime时间格式转换为Unix时间戳格式
        public static int DateTimeToStamp(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }


        //发送HTTP请求

        public static string http(string url = "")
        {

            string response = "";
            string strRequestUri = url == "" ? "http://www.junglecat7.com/Addons/license/license.php" : url;

            HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(strRequestUri);

            // 封装Cookie
            Uri uri = new Uri(strRequestUri);
            Cookie cookie = new Cookie("Name", ""); // 设置key、value形式的Cookie
            CookieContainer cookies = new CookieContainer();
            cookies.Add(uri, cookie);
            httpRequest.CookieContainer = cookies;


            // 封装Http Header
            httpRequest.Method = "Post";
            httpRequest.Referer = "";    //来源
            httpRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.89 Safari/537.36";
            httpRequest.Accept = "text/plain, */*; q=0.01";
            httpRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            httpRequest.Timeout = 1000 * 10;
            httpRequest.KeepAlive = true;


            // 通过流写入请求数据
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(""); // 设置编码
            try
            {
                httpRequest.ContentLength = bytes.Length;
                Stream requestStream = httpRequest.GetRequestStream();
                requestStream.Write(bytes, 0, bytes.Length);
                requestStream.Close(); // 关闭流


                // 获得应答报文
                HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();
                Stream responseStream = httpResponse.GetResponseStream();
                StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
                response = reader.ReadToEnd();
                reader.Close();
                responseStream.Close();

            }
            catch (Exception err)
            {

                return "";
            }


            return response;

        }

        public static bool ck()
        {
            
            SQLiteDBHelper db = new SQLiteDBHelper(Environment.CurrentDirectory + "\\data\\database.db3");

            string license = db.C("license")[0][1];
            string strPath = "";
            if (license.Length != 100)
            {

                return false;

            }

            byte[] bpath = Convert.FromBase64String(license);
            strPath = System.Text.ASCIIEncoding.Default.GetString(bpath);

            string license_code = "";
            string hid = "";


            int[] map = { 8, 12, 18, 22, 28, 38, 58, 35 };

            for (int i = 0; i < map.Length; i++)
            {

                license_code += strPath[map[i] - 1].ToString();

            }

            for (int j = 0; j < strPath.Length; j++)
            {

                if (j == 8 || j == 18 || j == 28 || j >= 63)
                {

                    hid += strPath[j];

                }
            }


            if (hid == common.GetDiskID() && license_code == db.C("license_code")[0][1])
            {

                Console.WriteLine("验证成功！");
                return true;

            }
            else
            {

                Console.WriteLine("验证失败！");
                return false;
            }
        }



        public static string GetDiskID()
        {
            try
            {
                String HDid = "";
                ManagementClass mc = new ManagementClass("Win32_DiskDrive");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    HDid = (string)mo.Properties["SerialNumber"].Value;
                }
                moc = null;
                mc = null;

                //string[] arr = Regex.Split(HDid, " ", RegexOptions.IgnoreCase);

                return HDid.ToString().Trim();
            }
            catch
            {
                return "unknow";
            }
            finally
            {


            }

        }


        public static string GetLocalIP()
        {
            string result = common.RunApp("route", "print", true);
            Match m = Regex.Match(result, @"0.0.0.0\s+0.0.0.0\s+(\d+.\d+.\d+.\d+)\s+(\d+.\d+.\d+.\d+)");
            if (m.Success)
            {
                return m.Groups[2].Value;
            }
            else
            {
                try
                {
                    System.Net.Sockets.TcpClient c = new System.Net.Sockets.TcpClient();
                    c.Connect("www.baidu.com", 80);
                    string ip = ((System.Net.IPEndPoint)c.Client.LocalEndPoint).Address.ToString();
                    c.Close();
                    return ip;
                }
                catch (Exception)
                {
                    return null;
                }
            }
        }



        /// <summary> 
        /// 运行一个控制台程序并返回其输出参数。 
        /// </summary> 
        /// <param name="filename">程序名</param> 
        /// <param name="arguments">输入参数</param> 
        /// <returns></returns> 
        public static string RunApp(string filename, string arguments, bool recordLog)
        {
            try
            {
                if (recordLog)
                {
                    Trace.WriteLine(filename + " " + arguments);
                }
                Process proc = new Process();
                proc.StartInfo.FileName = filename;
                proc.StartInfo.CreateNoWindow = true;
                proc.StartInfo.Arguments = arguments;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.UseShellExecute = false;
                proc.Start();
                using (System.IO.StreamReader sr = new System.IO.StreamReader(proc.StandardOutput.BaseStream, Encoding.Default))
                {
                    //string txt = sr.ReadToEnd(); 
                    //sr.Close(); 
                    //if (recordLog) 
                    //{ 
                    // Trace.WriteLine(txt); 
                    //} 
                    //if (!proc.HasExited) 
                    //{ 
                    // proc.Kill(); 
                    //} 
                    //上面标记的是原文，下面是我自己调试错误后自行修改的 
                    Thread.Sleep(100);  //貌似调用系统的nslookup还未返回数据或者数据未编码完成，程序就已经跳过直接执行 
                                        //txt = sr.ReadToEnd()了，导致返回的数据为空，故睡眠令硬件反应 
                    if (!proc.HasExited)  //在无参数调用nslookup后，可以继续输入命令继续操作，如果进程未停止就直接执行 
                    {    //txt = sr.ReadToEnd()程序就在等待输入，而且又无法输入，直接掐住无法继续运行 
                        proc.Kill();
                    }
                    string txt = sr.ReadToEnd();
                    sr.Close();
                    if (recordLog)
                        Trace.WriteLine(txt);
                    return txt;
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex);
                return ex.Message;
            }
        }


    }
}
